#Requires AutoHotkey v2.0
#SingleInstance Force

GetKet() {
  ; 获取et对象，避免com未注册
  try {
    return ComObjActive("Ket.Application")
  } catch {
    MsgBox "等待COM注册", , "0 T0.6"
    return ComObjActive("Ket.Application")
  }
}

GetKwps() {
  ; 获取wps对象，避免com未注册
  try {
    return ComObjActive("Kwps.Application")
  } catch {
    MsgBox "等待COM注册", , "0 T0.6"
    return ComObjActive("Kwps.Application")
  }
}

GetJS(url) {
  WebRequest := ComObject("WinHttp.WinHttpRequest.5.1")
  WebRequest.Open("GET", url, false)
  WebRequest.Send()
  return WebRequest.ResponseText
}

Dice(fst, snd) {
    if (StrLen(fst) < 2 || StrLen(snd) < 2) {
        return 0
    }
    m := Map()
    loop StrLen(fst) - 1 {
      s := SubStr(fst, A_Index, 2)
      if m.Has(s) {
        m[s] += 1
      } else {
        m[s] := 1
      }
    }
    match := 0
    loop StrLen(snd) - 1 {
      s := SubStr(snd, A_Index, 2)
      if m.Has(s) and m[s] > 0 {
        match++
        m[s] -= 1
      }
    }
    return 2.0 * match / (StrLen(fst) + StrLen(snd) - 2)
}

; WPS
#HotIf WinActive("ahk_exe wps.exe")
  MButton::
  {
    A_Clipboard := A_Clipboard
    ClipWait 0.1
    SendEvent "{LButton}^v"
  }
  XButton1::
  {
    et := GetKet()
    et.Selection.SpecialCells(12).Select
    A_Clipboard := et.WorksheetFunction.Sum(et.Selection)
    ClipWait 0.1
    et := ""
    ToolTip "Sum: " . A_Clipboard
    SetTimer () => ToolTip(), -1000
  }
  XButton2::
  {
    et := GetKet()
    et.ScreenUpdating := false
    s0 := et.Selection
    Send "{LButton}"
    Sleep 100
    s1 := et.Selection
    s0.Select
    s1.Activate
    et.ScreenUpdating := true
    et := ""
  }
  #[::
  #]::
  {
    et := GetKet()
    if (A_ThisHotkey == "#[") {
      static t
      t := et.Selection.Address(,,,true)
      Send "^["
    } else {
      try {
        RegExMatch(t, "\[(.*)\](.*)!(.*)", &m)
        et.Workbooks(m[1]).Sheets(m[2]).Activate
        et.Range(m[3]).Select
      }
    }
    et := ""
  }
  #m::
  {
    et := GetKet()
    n := et.WorksheetFunction.Sum(et.Selection)
    et.Selection.Merge
    et.Selection.Value2 := n
    et := ""
  }
  /* #s::
  {
    MyGui := Gui("+AlwaysOnTop")
    MyGui.SetFont("s16")
    MyGui.MarginX := 0
    MyGui.MarginY := 0
    LB := MyGui.Add("ListBox", "r30 w200")
    LB.OnEvent("Change", LB_Change)
    et := GetKet()
    shts := et.Sheets
    for s in shts {
      LB.Add([s.Name])
    }
    MyGui.OnEvent("Close", MyGui_Close)
    MyGui.Show "x0"

    MyGui_Close(*)
    {
      et := ""
    }

    LB_Change(x, *)
    {
      try
        shts[x.Text].Select
    }
  } */
  #f::
  {
    et := GetKet()
    if et.Selection.Formula == "" {
      try {
        et.Selection.Formula := et.Selection.Text
      } catch {
        MsgBox "请输入区域或名称"
      }
    } else {
      et.Selection.Text := et.Selection.Formula
      et.Selection.Formula := ""
    }
    et := ""
  }
  #Tab::
  {
    et := GetKet()
    if (IsSet(p)) {
      t := et.ActiveSheet.Name
      et.Sheets[p].Select
      p := t
    } else {
      static p := et.ActiveSheet.Name
    }
    et := ""
  }
  NumpadEnter::
  {
    static n := 0
    if (A_PriorHotkey = A_ThisHotkey and A_TimeSincePriorHotkey < 300) {
      Send Format("{{}Down{}}{{}Left {}{}}", n)
      n := 0
    } else {
      Send "{Right}"
      n += 1
    }
  }
  #v::
  {
    et := GetKet()
    t := et.Selection.SpecialCells(12)
    arr := []
    for i in StrSplit(RegExReplace(A_Clipboard, "`r?`n$"), "`n", "`r") {
      for j in StrSplit(i, "`t") {
        arr.Push(j)
      }
    }
    if (arr.Length = t.Count) {
      t.Select
      for i in et.Selection {
        i.Value2 := arr[A_Index]
      }
    } else {
      MsgBox "不能粘贴大小不同的区域", , "0 T0.6"
    }
    et := ""
  }
  #p::
  {
    static js := GetJS("https://cdn.bootcdn.net/ajax/libs/excel-formula/1.5.0/excel-formula.min.js")
    hf := ComObject("htmlfile")
    hf.parentWindow.execScript(js)
    et := GetKet()
    f := hf.parentWindow.excelFormulaUtilities.formatFormula(et.Selection[1].Formula)
    f := RegExReplace(f, "(`t*`n)+", "`n")
    et.Selection[1].Formula := RegExReplace(f, "`t", " ")
    et := ""
    hf := ""
  }
  #+Enter::
  #Enter::
  {
    static lst
    if (A_ThisHotkey = "#+Enter") {
      et := GetKet()
      lst := []
      for i in et.Selection {
        lst.Push(i.Text)
      }
      et := ""
      MsgBox "导入成功", , "0 T0.6"
      return
    }
    w := WinGetID("A")
    MyGui := Gui("+AlwaysOnTop")
    MyGui.SetFont("s16")
    MyGui.MarginX := 0
    MyGui.MarginY := 0
    ED := MyGui.Add("Edit", "w200")
    ED.OnEvent("Change", ED_Change)
    LB := MyGui.Add("ListBox", "r20 w200")
    HotIfWinActive "ahk_id " MyGui.Hwnd
    Hotkey "Tab", MyGui_Key
    Hotkey "Enter", MyGui_Key
    HotIfWinActive
    for i in lst {
      LB.Add([i])
    }
    MyGui.OnEvent("Close", MyGui_Close)
    MyGui.Show

    MyGui_Close(*)
    {
      HotIfWinActive "ahk_id " MyGui.Hwnd
      Hotkey "Tab", "Off"
      Hotkey "Enter", "Off"
      HotIfWinActive
    }

    MyGui_Key(k)
    {
      if (k = "Tab") {
        if (LB.Value = ControlGetItems(LB).Length) {
          LB.Choose(1)
        } else {
          LB.Choose(LB.Value + 1)
        }
      }
      else if (k = "Enter") {
        WinActivate w
        WinWaitActive w
        SendText LB.Text
        SendEvent "{Enter}"
        WinClose MyGui
      }
    }

    ED_Change(*) {
      SetTimer After400, -400
    }

    After400() {
      m := Map()
      for i in lst {
        m[i] := Dice(ED.Text, i)
      }
      loop lst.Length - 1 {
        loop lst.Length - A_Index {
          if m[lst[A_Index]] < m[lst[A_Index + 1]] {
            t := lst[A_Index]
            lst[A_Index] := lst[A_Index + 1]
            lst[A_Index + 1] := t
          }
        }
      }
      LB.Opt("-Redraw")
      LB.Delete
      for i in lst {
        LB.Add([i])
      }
      LB.Opt("+Redraw")
      LB.Choose(1)
    }
  }
  #h::
  {
    et := GetKet()
    et.ScreenUpdating := false
    et.DisplayAlerts := false
    sel := et.Selection
    sht := et.Sheets.Add()
    rng := sht.Range("A1")
    sel.Copy(rng)
    w := 0
    for i in rng.MergeArea {
      w += Round(i.ColumnWidth, 2)
    }
    rng.UnMerge()
    rng.ColumnWidth := Ceil(w)
    rng.WrapText := true
    rng.EntireRow.AutoFit()
    sel.WrapText := true
    sel.RowHeight := rng.RowHeight
    sht.Delete()
    et.ScreenUpdating := true
    et.DisplayAlerts := true
    et := ""
  }
  #a::
  {
    clsnn := ControlGetClassNN(ControlGetFocus("A"), "A")
    if clsnn == "_WwG1" {
      wps := GetKwps()
      t := wps.Selection.Type
      if t == 8 {
        st := wps.Selection.ShapeRange(1).Type
        for i in wps.ActiveDocument.Shapes {
          if i.Type == st {
            i.Select(0)
          }
        }
      } else {
        if t == 7 {
          s := wps.ActiveDocument.InlineShapes
        } else if t == 4 or t == 5 {
          s := wps.ActiveDocument.Tables
        } else {
          s := wps.ActiveDocument.Paragraphs
        }
        wps.ActiveDocument.DeleteAllEditableRanges(-1)
        for i in s {
          i.Range.Editors.Add(-1)
        }
        wps.ActiveDocument.SelectAllEditableRanges(-1)
        wps.ActiveDocument.DeleteAllEditableRanges(-1)
      }
      wps := ""
    } else if clsnn == "EXCEL71" {
      et := GetKet()
      a := et.Selection.CurrentArray
      if a.Address() != "'#REF!'!#REF!" {
        a.Select
      } else {
        et.Selection.CurrentRegion.Select
      }
      et := ""
    }
  }
  #=::
  {
    wps := GetKwps()
    if wps.Selection.Type == 7 {
      for i in wps.ActiveDocument.InlineShapes {
        i.LockAspectRatio := 0
        i.Width := wps.Selection.InlineShapes(1).Width
        i.Height := wps.Selection.InlineShapes(1).Height
      }
    } else if wps.Selection.Type == 8 {
      for i in wps.ActiveDocument.Shapes {
        i.LockAspectRatio := 0
        i.Width := wps.Selection.ShapeRange(1).Width
        i.Height := wps.Selection.ShapeRange(1).Height
      }
    }
    wps := ""
  }
  ; LButton::
  ; {
  ;   static s := RegRead("HKCU\Control Panel\Mouse", "DoubleClickSpeed", 600)
  ;   MouseGetPos , , , &WhichControl
  ;   if WhichControl == "EXCEL71" and A_PriorHotkey == A_ThisHotkey and A_TimeSincePriorHotkey < s {
  ;     Send "{F2}"
  ;   } else {
  ;     Send "{LButton Down}"
  ;     KeyWait "LButton"
  ;     Send "{LButton Up}"
  ;   }
  ; }
#HotIf
  #t::
  {
    ExStyle := WinGetExStyle("A")
    if (ExStyle & 0x8) {
      WinSetTransparent "", "A"
      WinSetAlwaysOnTop 0, "A"
    } else {
      WinSetTransparent 200, "A"
      WinSetAlwaysOnTop 1, "A"
    }
  }